package a66weding.com.jiehuntong.activity.me;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.xutils.x;

import java.io.File;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.activity.imageupload.activity.AlbumActivity;
import a66weding.com.jiehuntong.activity.imageupload.activity.GalleryActivity;
import a66weding.com.jiehuntong.activity.imageupload.activity.util.Bimp;
import a66weding.com.jiehuntong.activity.imageupload.activity.util.FileUtils;
import a66weding.com.jiehuntong.activity.imageupload.activity.util.ImageItem;
import a66weding.com.jiehuntong.activity.imageupload.activity.util.Res;
import a66weding.com.jiehuntong.activity.order.ApplyServiceOneActivity;
import a66weding.com.jiehuntong.application.DataWareHourse;
import a66weding.com.jiehuntong.application.GlobalApplication;
import a66weding.com.jiehuntong.beans.CommonResultBean;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.MyOrderBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.beans.UpLoadImage;
import a66weding.com.jiehuntong.beans.WxremindBean;
import a66weding.com.jiehuntong.common.MessageEvent;
import a66weding.com.jiehuntong.common.uploadimage.HttpFileAsycTask;
import a66weding.com.jiehuntong.common.uploadimage.HttpFileUpTool;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.FileUtil;
import a66weding.com.jiehuntong.common.utils.ImageOptionsUtil;
import a66weding.com.jiehuntong.common.utils.Tools;
import a66weding.com.jiehuntong.common.utils.uploadimage.UpLoadUtil;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.NetStatusUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import a66weding.com.jiehuntong.widgets.NoScrollGridView;

/**
 * 我的-订单-评价界面
 * Created by Administrator on 2016/7/11.
 */
public class MeIndentEvaluateActivity extends MeBaseActivity implements View.OnClickListener, OnNetResultListener, AlbumActivity.OnPicChangeListener {
    private LinearLayout mBackLay;
    private TextView mBackContentTv;
    private TextView mHeaderTitleTv;
    private RelativeLayout mHeaderRightRlay;

    private RatingBar mThingBar;
    private RatingBar mServiceBar;
    private RatingBar mExpressBar;
    private RatingBar mCustomServiceBar;
    private EditText mLableTitleEt;
    private EditText mLableContentEt;

    private Button mCommitBtn;

    private PopupWindow pop = null;
    //需要动画的pop布局;
    private LinearLayout ll_popup;
    private static final int TAKE_PICTURE = 0x000001;
    //适配器
    private GridAdapter adapter;
    //gridView
    private NoScrollGridView evalua_grid;
    //整体布局
    private RelativeLayout ev_group;
    //是否是匿名评价
    private CheckBox isAnonymous;

    private boolean flag;//如果为true 就是就是匿名,false 为实名;

    public static final int GETPICRESULT = 5;

    private static final int PICSUCESS = 10;
    private static final int PICERROR = 11;

    private static final int PERMISSION_CAMERA = 5;

    private static int picNums = 0;
    private MyOrderBean.DataBean.MyOrderDetailBean orderDetailBean;
    //图片
    private ImageView indent_evaluate_image;
    //集合获取图片上传封装的对象
    private List<UpLoadImage> upimagList;
    //
    private int whichflag;
    private ArrayList<ImageItem> tempSelectBitmapList;

    private StringBuffer picSb = new StringBuffer();
    private int goodsScore;
    private int serviceScore;
    private int expressScore;
    private int customServiceScore;
    private TextView mIndentTv;
    private static int requestCount = 0;
    public static boolean isTakePhoto;

    private PopupWindow mProgresspop;
    private ProgressBar mProgressbar;
    private TextView mProgressTv;
    private static final int PROGRESS = 8;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_me_indent_evaluate1);

        Res.init(this);
        Intent intent = getIntent();
        if (intent != null) {
            ArrayList<String> picpath = intent.getStringArrayListExtra("picpath");
            orderDetailBean = (MyOrderBean.DataBean.MyOrderDetailBean) intent.getSerializableExtra("EvaluationAdapter");
            whichflag = intent.getIntExtra("flag", -1);
        }

        ((GlobalApplication) getApplication()).getActivityManager().addActivity("MeIndentEvaluateActivity", this);

        init();
        initview();
        initData();

        EventBus.getDefault().register(this);
    }

    /**
     * 初始化数据;
     */
    private void initData() {
        //图片上传的集合;
        upimagList = new ArrayList<>();
        x.image().bind(indent_evaluate_image, orderDetailBean.getProductPicMain(), ImageOptionsUtil.getcircle_fixy());

    }

    private void initview() {
        indent_evaluate_image = (ImageView) findViewById(R.id.indent_evaluate_image);
        isAnonymous = (CheckBox) findViewById(R.id.isAnonymous);
        ev_group = (RelativeLayout) findViewById(R.id.ev_group);
        evalua_grid = (NoScrollGridView) findViewById(R.id.evalua_grid);
        if(!isTakePhoto){
            Bimp.getInstance().getTempSelectBitmap().clear();
            Bimp.max = 0;
        }
        adapter = new GridAdapter(this);
        adapter.update();
        evalua_grid.setAdapter(adapter);
        mBackLay = (LinearLayout) findViewById(R.id.llay_header_back);
        mBackContentTv = (TextView) findViewById(R.id.tv_header_backcontent);
        mHeaderTitleTv = (TextView) findViewById(R.id.tv_header_title);
        mHeaderRightRlay = (RelativeLayout) findViewById(R.id.rlay_header_rightfunc);

        mThingBar = (RatingBar) findViewById(R.id.ratingBar);
        mServiceBar = (RatingBar) findViewById(R.id.serve_ratingBar);
        mExpressBar = (RatingBar) findViewById(R.id.expressage_ratingBar);
        mCustomServiceBar = (RatingBar) findViewById(R.id.service_ratingBar);
        mLableTitleEt = (EditText) findViewById(R.id.et_title);
        mLableContentEt = (EditText) findViewById(R.id.et_lable_content);
        mIndentTv = (TextView) findViewById(R.id.tv_me_indent);
        mIndentTv.setText(orderDetailBean.getProductName());

        mBackContentTv.setText("返回");
        mHeaderTitleTv.setText("评价晒单");
        mHeaderRightRlay.setVisibility(View.GONE);

        mCommitBtn = (Button) findViewById(R.id.btn_commit);

        mBackLay.setOnClickListener(this);

        //当点击item的时候进入下一个界面;
        evalua_grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == Bimp.getInstance().getTempSelectBitmap().size()) {
                    ll_popup.startAnimation(AnimationUtils.loadAnimation(MeIndentEvaluateActivity.this, R.anim.activity_translate_in));
                    pop.showAtLocation(ev_group, Gravity.BOTTOM, 0, 0);
                } else {
                    Intent intent = new Intent(MeIndentEvaluateActivity.this, GalleryActivity.class);
                    intent.putExtra("position", "1");
                    intent.putExtra("ID", position);

                    startActivity(intent);
                }
            }
        });

        mCommitBtn.setOnClickListener(this);

        /**
         * checkBox的监听;
         */
        isAnonymous.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    memberID = 0;
                } else {

                }
            }
        });


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.llay_header_back: //点击返回，退出当前界面
                isTakePhoto=false;
                finish();
                break;
            case R.id.btn_commit: //提交
                boolean isCheckRight = chenkContent();
                picNums = 0;
                if (isCheckRight) {
                    requestCount = 0;

                    tempSelectBitmapList = Bimp.getInstance().getTempSelectBitmap();
                    picSb.delete(0, picSb.length());
                    if (this.tempSelectBitmapList != null && tempSelectBitmapList.size() > 0) {

                        processBitmap(tempSelectBitmapList);
                        picNums = 0;
                        boolean iswifi = NetStatusUtil.isWifi(this);
                        boolean is4g = NetStatusUtil.is4G(this);
                        if (iswifi || is4g) {
                            updatePics();
                        } else {
                            showDialog();
                        }
                    } else {
                        commitPinjia();
                    }
                }

                break;
        }
    }


    private void showDialog() {
        AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);
        builder.setMessage("检测到您的网络处于非wifi状态或非4g状态,上传图片将消耗一定的流量,是否继续?");
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                updatePics();
                dialog.dismiss();
            }
        });
        builder.show();

    }

    //上传图片;
    private void updatePics() {
        showProgressPopupWindow( mCommitBtn);
        String picUrl = RequestCode.PostUploadTuiHuanHuo;
        picUrl += "&memberMobile=" + memberID;
        mCommitBtn.setEnabled(false);
        final String finalPicUrl = picUrl;
        new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < tempSelectBitmapList.size(); i++) {
                    String imagePath = tempSelectBitmapList.get(i).getImagePath();
                    if (!TextUtils.isEmpty(imagePath)) {
                        File picfile = new File(imagePath);
                        requestCount++;
                        uploadePic(picfile, finalPicUrl);
                    }
                }
            }
        }.start();
    }

    /**
     * 上传 评价;
     *
     * @return
     */
    private String commitPinjia() {
        showCommitPopupWindow(this, mCommitBtn);
        String url = RequestCode.post_OrderPingJia;

        goodsScore = (int) (mThingBar.getRating() * 2);
        serviceScore = (int) (mServiceBar.getRating() * 2);
        expressScore = (int) (mExpressBar.getRating() * 2);
        customServiceScore = (int) (mCustomServiceBar.getRating() * 2);
        String mTitle = mLableTitleEt.getText().toString().trim();
        String mLableContent = mLableContentEt.getText().toString().trim();

        int productNumberId = orderDetailBean.getDetailID();
        //返回图片长传的路径字段
        memberID = DataWareHourse.getInstance().getmUser().getData().get(0).getI_Id();

        String pics = "";
        if (picSb.toString().length() > 5) {
            pics = picSb.toString();
        }
        url += "&id=" + productNumberId + "&score1=" + goodsScore + "&score2=" + serviceScore + "&score3=" + expressScore + "&score4=" + customServiceScore
                + "&memeberID=" + memberID + "&pics=" + pics + "&title=" + changeUft(mTitle) + "&content=" + changeUft(mLableContent);
        HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url, this, WxremindBean.class, RequestCode.post_OrderPingJia);
        HttpHandleUtil.executeCommonPost(this, httpRequestBean);
        return "";
    }

    @Override
    protected void onResume() {
        super.onResume();
        adapter.update();
    }

    //将汉字进行转码
    private String changeUft(String content) {
        String word = null;
        try {
            word = URLEncoder.encode(content, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return word;
    }

    private void uploadePic(File picFile, String url) {
        if (picFile == null) {
            return;
        }
        UpLoadUtil upLoadUtil = new UpLoadUtil(url, picFile, new UpLoadUtil.ResultCallBack() {
            @Override
            public void getResult(UpLoadImage upLoadImage) {
                String resCode = upLoadImage.getResCode();
                if ("0000".equals(resCode)) {
                    picSb.append(upLoadImage.getResult().getUrlField() + ";");
                    picNums++;
                    int progress = (int) (((picNums*1f) / (tempSelectBitmapList.size()*1f))*100);
                    Message message = new Message();
                    message.what=PROGRESS;
                    message.arg1=progress;
                    handler.sendMessage(message);
                } else {
                    Message message = new Message();
                    message.arg1 = picNums;
                    message.what = PICERROR;
                    handler.sendMessage(message);
                }

                if (picNums == tempSelectBitmapList.size()) {
                    handler.sendEmptyMessage(PICSUCESS);

                }
            }
        });

        upLoadUtil.uploadFile(picFile, url);

    }


    private void init() {
        pop = new PopupWindow(this);
        View view = getLayoutInflater().inflate(R.layout.item_popupwindows, null);
        ll_popup = (LinearLayout) view.findViewById(R.id.ll_popup);
        pop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        pop.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        pop.setBackgroundDrawable(new BitmapDrawable());
        pop.setFocusable(true);
        pop.setOutsideTouchable(true);
        pop.setContentView(view);

        RelativeLayout parent = (RelativeLayout) view.findViewById(R.id.parent);
        Button bt1 = (Button) view
                .findViewById(R.id.item_popupwindows_camera);
        Button bt2 = (Button) view
                .findViewById(R.id.item_popupwindows_Photo);
        Button bt3 = (Button) view
                .findViewById(R.id.item_popupwindows_cancel);
        parent.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                pop.dismiss();
                ll_popup.clearAnimation();
            }
        });
        bt1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //拍照;
                photo();

                pop.dismiss();
                ll_popup.clearAnimation();
            }
        });
        bt2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //进入相册浏览界面;
                Intent intent = new Intent(MeIndentEvaluateActivity.this, AlbumActivity.class);
                intent.putExtra("EvaluationAdapter", orderDetailBean);
                intent.putExtra("flag", whichflag);
                startActivity(intent);
                overridePendingTransition(R.anim.activity_translate_in, R.anim.activity_translate_out);
                pop.dismiss();
                ll_popup.clearAnimation();
            }
        });
        bt3.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                pop.dismiss();
                ll_popup.clearAnimation();
            }
        });
    }

    /**
     * 进入照相的镜面;
     */
    public void photo() {
        isTakePhoto=true;
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            //申请MOUNT_UNMOUNT_FILESYSTEMS权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_CAMERA);
        } else {
            Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(openCameraIntent, TAKE_PICTURE);
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        doNext(requestCode, grantResults);
    }


    private void doNext(int requestCode, int[] grantResults) {
        if (requestCode == PERMISSION_CAMERA) {
            if (grantResults.length > 0 && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {

                Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(openCameraIntent, TAKE_PICTURE);

            } else {
                CUtils.showToast("请打开手机拍照权限后在操作");
            }
        }
    }

    private CommonResultBean resultBean;

    /**
     * @param sucessbean 通信返回的数据
     */
    @Override
    public void onSucess(SuccessBean sucessbean) {
        Object data = sucessbean.getData();

        if (mCommitpop != null) {
            mCommitpop.dismiss();
        }
        isTakePhoto=false;
        if (data instanceof WxremindBean) {
            WxremindBean resultData = (WxremindBean) data;
            if (resultData.isResult()) {
                CUtils.showToast(resultData.getMsg());

                MessageEvent messageEvent = new MessageEvent();
                messageEvent.setWhichisPinlun(whichflag);
                EventBus.getDefault().post(messageEvent);

                mCommitBtn.setEnabled(false);

                try {
                    Activity applyServicePreFirstActivity = ((GlobalApplication) getApplication()).getActivityManager().getActivity("ApplyServiceOneActivity");
                    Activity evaluationActivity = ((GlobalApplication) getApplication()).getActivityManager().getActivity("EvaluationActivity");
                    if (applyServicePreFirstActivity != null) {
                        applyServicePreFirstActivity.finish();
                    }
                    if (evaluationActivity != null) {
                        evaluationActivity.finish();
                    }
                    File tempDir = new File(FileUtil.getImgFile(this), "pinjia");
                    File[] files = tempDir.listFiles();
                    for (int i = 0; i < files.length; i++) {
                        files[i].delete();
                    }

                }catch (Exception e){
                }



                Intent intent = new Intent(MeIndentEvaluateActivity.this, MeIndentActivity.class);
                startActivity(intent);
                finish();
            } else {
                CUtils.showToast(resultData.getMsg());
            }
        }

    }

    @Override
    public void onError(ErrorBean errorBean) {
        if (mCommitpop != null) {
            mCommitpop.dismiss();
        }
        isTakePhoto=false;
        mCommitBtn.setEnabled(true);
        CUtils.showDataErrToast(this);
    }

    @Override
    public void onPicChange() {
        if (adapter != null) {
            adapter.update();
        }
    }

    @Subscribe
    public void onEventMsg(MessageEvent msg) {

        if (adapter != null) {
            adapter.update();
        }

    }


    public class GridAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        private int selectedPosition = -1;
        private boolean shape;

        public boolean isShape() {
            return shape;
        }

        public void setShape(boolean shape) {
            this.shape = shape;
        }

        public GridAdapter(Context context) {
            inflater = LayoutInflater.from(context);
        }

        public void update() {
            loading();
        }


        @Override
        public int getCount() {
            if (Bimp.getInstance().getTempSelectBitmap().size() == 5) {
                return 5;
            }
            return (Bimp.getInstance().getTempSelectBitmap().size() + 1);

        }

        public void setSelectedPosition(int position) {
            selectedPosition = position;
        }

        public int getSelectedPosition() {
            return selectedPosition;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.item_published_grida,
                        parent, false);
                holder = new ViewHolder();
                holder.image = (ImageView) convertView
                        .findViewById(R.id.item_grida_image);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            if (position == Bimp.getInstance().getTempSelectBitmap().size()) {
                holder.image.setImageBitmap(BitmapFactory.decodeResource(
                        getResources(), R.mipmap.icon_addpic_unfocused));
                //当有5张图片的时候
                if (position == 5) {
                    holder.image.setVisibility(View.GONE);
                }
            } else {
                holder.image.setImageBitmap(Bimp.getInstance().getTempSelectBitmap().get(position).getBitmap());
            }
            return convertView;
        }

        public void loading() {
            new Thread(new Runnable() {
                public void run() {
                    while (true) {
                        if (Bimp.max == Bimp.getInstance().getTempSelectBitmap().size()) {
                            Message message = new Message();
                            message.what = 1;
                            handler.sendMessage(message);
                            break;
                        } else {
                            Bimp.max += 1;
                            Message message = new Message();
                            message.what = 1;
                            handler.sendMessage(message);
                        }
                    }
                }
            }).start();
        }

        public class ViewHolder {
            public ImageView image;
        }
    }

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    adapter.notifyDataSetChanged();
                    break;
                case PICSUCESS://上传图片成功
                    if(mProgresspop.isShowing()){
                        mProgresspop.dismiss();
                    }
                    commitPinjia();
                    break;
                case PICERROR://上传未完全成功
                    int number = msg.arg1;
                    CUtils.showToast("图片" + number + "上传失败，请重新选择图片上传");
                    if(mProgresspop.isShowing()){
                        mProgresspop.dismiss();
                    }
                    if(mCommitpop.isShowing()){
                        mCommitpop.dismiss();
                    }
                    break;
                case PROGRESS://上传进度
                    if(mProgresspop.isShowing()){
                        int progress = msg.arg1;
                        mProgressbar.setProgress(progress);
                        mProgressTv.setText("正在上传  " +progress+  "%");
                    }
            }
            super.handleMessage(msg);
        }
    };


    private String getStringFromUpImg(List<UpLoadImage> list) {
        if (list.size() == 0) {
            return null;
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < list.size(); i++) {
            if (i == 0) {
                sb.append(list.get(i));
            } else {
                sb.append(";" + list.get(i));
            }
        }
        return sb.toString();
    }

    private boolean chenkContent() {
        String mTitle = mLableTitleEt.getText().toString().trim();
        if (TextUtils.isEmpty(mTitle)) {
            CUtils.showToast("标签标题不能为空");
            return false;
        }
        String mLableContent = mLableContentEt.getText().toString().trim();
        if (TextUtils.isEmpty(mLableContent)) {
            CUtils.showToast("评价内容不能为空");
            return false;
        }
        goodsScore = (int) (mThingBar.getRating() * 2);
        serviceScore = (int) (mServiceBar.getRating() * 2);
        expressScore = (int) (mExpressBar.getRating() * 2);
        customServiceScore = (int) (mCustomServiceBar.getRating() * 2);
        if (goodsScore == 0) {
            CUtils.showToast("商品评分不能为空");
            return false;
        }
        if (serviceScore == 0) {
            CUtils.showToast("服务评分不能为空");
            return false;
        }
        if (expressScore == 0) {
            CUtils.showToast("快递服务评分不能为空");
            return false;
        }
        if (customServiceScore == 0) {
            CUtils.showToast("客服服务评分不能为空");
            return false;
        }
        return true;
    }


    /**
     * 获取路径;
     *
     * @param s
     * @return
     */
    public String getString(String s) {
        String path = null;
        if (s == null)
            return "";
        for (int i = s.length() - 1; i > 0; i++) {
            s.charAt(i);
        }
        return path;
    }

    @Override
    protected void onRestart() {
        adapter.update();
        super.onRestart();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            case TAKE_PICTURE://照相
                if (data != null) {
                    if (Bimp.getInstance().getTempSelectBitmap().size() < 5 && resultCode == RESULT_OK) {
                        try {
                            String fileName = String.valueOf(System.currentTimeMillis());
                            Bitmap bm = (Bitmap) data.getExtras().get("data");
                            File tempDir = new File(FileUtil.getImgFile(this), "pinjia");
                            if (!tempDir.exists()) {
                                tempDir.mkdirs();
                            }
                            File tempPath = new File(tempDir, fileName + ".jpg");
                            FileOutputStream out = new FileOutputStream(tempPath);
                            bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
                            out.flush();
                            out.close();
//                            FileUtils.saveBitmap(bm, fileName);
                            ImageItem takePhoto = new ImageItem();
                            takePhoto.setBitmap(bm);
                            takePhoto.setImagePath(tempPath.getAbsolutePath());
                            takePhoto.setSelected(true);
                            Bimp.getInstance().getTempSelectBitmap().add(takePhoto);
                            adapter.update();

                        } catch (Exception e) {

                        }

                    }
                }
                break;
            case GETPICRESULT:
                if (data != null) {
                    ArrayList<String> picpathList = data.getStringArrayListExtra("picpath");
                }

                break;
        }
    }


    private void processBitmap(ArrayList<ImageItem> tempSelectBitmapList) {

        for (int i = 0; i < tempSelectBitmapList.size(); i++) {
            int byteCount1 = tempSelectBitmapList.get(i).getBitmap().getByteCount();

            String imagePath = tempSelectBitmapList.get(i).getImagePath();

            Bitmap newBitmap = compressBySize(imagePath, 320, 320);
            File tempDir = new File(FileUtil.getImgFile(this), "pinjia");
            if (!tempDir.exists()) {
                tempDir.mkdirs();
            }
            String fileName = String.valueOf(System.currentTimeMillis());
            try {
                File tempPath = new File(tempDir, i + "" + fileName + ".jpg");

                FileOutputStream out = new FileOutputStream(tempPath);
                newBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
                out.flush();
                out.close();
                tempSelectBitmapList.get(i).setImagePath(tempPath.getAbsolutePath());

            }catch (Exception e){
            }

//            indent_evaluate_image.setImageBitmap(newBitmap);
            tempSelectBitmapList.get(i).setBitmap(newBitmap);
            int byteCount = tempSelectBitmapList.get(i).getBitmap().getByteCount();

        }

    }

    //压缩图片尺寸
    public Bitmap compressBySize(String pathName, int targetWidth,
                                 int targetHeight) {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;// 不去真的解析图片，只是获取图片的头部信息，包含宽高等；
        Bitmap bitmap = BitmapFactory.decodeFile(pathName, opts);
        // 得到图片的宽度、高度；
        float imgWidth = opts.outWidth;
        float imgHeight = opts.outHeight;
        // 分别计算图片宽度、高度与目标宽度、高度的比例；取大于等于该比例的最小整数；
        int widthRatio = (int) Math.ceil(imgWidth / (float) targetWidth);
        int heightRatio = (int) Math.ceil(imgHeight / (float) targetHeight);
        opts.inSampleSize = 1;
        if (widthRatio > 1 || widthRatio > 1) {
            if (widthRatio > heightRatio) {
                opts.inSampleSize = widthRatio;
            } else {
                opts.inSampleSize = heightRatio;
            }
        }
        //设置好缩放比例后，加载图片进内容；
        opts.inJustDecodeBounds = false;
        bitmap = BitmapFactory.decodeFile(pathName, opts);
        return bitmap;
    }


    private void showProgressPopupWindow(Button mCommitBtn) {

        View contentView = LayoutInflater.from(this).inflate(R.layout.progress_upload, null);
        mProgressbar = (ProgressBar) contentView.findViewById(R.id.pic_updata_progress);
        mProgressTv = (TextView) contentView.findViewById(R.id.tv_progress);

        mProgressbar.setMax(100);

        mProgresspop = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);

        //点击空白处时，隐藏掉pop窗口
        mProgresspop.setTouchable(true);

        mProgresspop.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.whitetranslucenthalf2)));

        contentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mProgresspop.dismiss();
            }
        });


        //设置位置
        mProgresspop.showAtLocation(mCommitBtn, Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL,0,0);//设置在屏幕中的显示位置

    }



    /**
     * 从写系统的返回按键;
     *
     * @param keyCode
     * @param event
     * @return
     */
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        if(!isTakePhoto){
            Bimp.getInstance().getTempSelectBitmap().clear();
            Bimp.max = 0;
        }
        super.onDestroy();
    }
}
